var fs = require("fs");
var express = require("express");
var server = express();
var expressStatic = require("express-static");
var mysql = require("mysql");
var url = require("url");
var sql = mysql.createConnection({
	host:"localhost",
	user:"root",
	password:"admin",
	database:"todolist"
})
var port = 82;
// 链接
sql.connect();

server.get("/register",(req,res)=>{
	var telephone = url.parse(req.url,true).query.telephone;
	var password = url.parse(req.url,true).query.password;
	var name = url.parse(req.url,true).query.name;
	sql.query(`insert into todolista (telephone,password,name) values("${telephone}","${password}","${name}")`,(error,data)=>{
		if(!error){
			console.log("注册成功")
			res.end("注册成功")
		}
		else{
			console.log("注册失败")
			res.end("注册失败")	
		}
	})
})

server.get("/sign-in",(req,res)=>{
	var telephone = url.parse(req.url,true).query.telephone;
	var password = url.parse(req.url,true).query.password;
	telephone1 = telephone;
	sql.query(`select password,name from todolista where telephone="${telephone}"`,(error,data)=>{
		if(!error && password === data[0].password){
			name = data[0].name;
			console.log("登陆成功")
			res.end("登陆成功")
		}
		else{
			console.log("登陆失败")
			res.end("登陆失败")
		}
	})
})

server.get("/storage",(req,res)=>{
	var list = url.parse(req.url,true).query.list;
	var list1 = url.parse(req.url,true).query.list1;
	sql.query(`UPDATE todolista SET list='${list}',list1='${list1}' WHERE telephone="${telephone1}"`,(error,data)=>{
		if(!error){
			console.log("缓存储入成功")
			res.end("")
		}
		else{
			console.log("缓存储入失败")
			res.end("")
		}
	})
})

server.get("/storage-list",(req,res)=>{
	sql.query(`select list,list1 from todolista where telephone="${telephone1}"`,(error,data)=>{
		if(!error){
			console.log("返回数据成功")
			res.end(JSON.stringify(data));
		}
		else{
			console.log("返回数据失败")
			res.end("返回数据失败")
		}
	})
})

server.use(expressStatic(`${__dirname}/ToDoList`));
//指明监听端口
server.listen(port)
console.log(`running of ${port}`)